package com.lagou.rpc;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class ServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        /*if(msg.toString().startsWith("UserService")){
            UserServiceImpl userService = new UserServiceImpl();
            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        }*/


        /**
         * 反射调用 UserService 实例
         */
        RpcRequest req = (RpcRequest) msg;
        Object bean = SpringUtil.getBean(req.getClassName());
        if (null == bean){
            bean = req.getClassName().newInstance();
        }

        Method method = bean.getClass().getMethod(req.getMethodName(), req.getParameterTypes());
        Object res = method.invoke(bean, req.getParameters());

        RpcResponse response = new RpcResponse();
        response.setRequestId(req.getRequestId());
        response.setMsg(null);
        response.setResult(res);
        // 写回数据
        ctx.writeAndFlush(response);

    }
}
